import React, {useState, useRef} from 'react';
import {Modal, Button} from 'antd';

import axios from 'axios';
import useGlobal from '../../hooks/useGlobal';

function Login() {
  const Global = useGlobal();
  const [code, setCode] = useState(null);
  const s = useRef(-1);

  const getCode = () => {
    axios.get('https://evp.51job.com/51job/api/1.0/index.php/msd/admin/qrcode').then(res => {
      setCode(res.data.data.url);
      s.current = setInterval(() => {
        axios.get('https://evp.51job.com/51job/api/1.0/index.php/msd/admin/notify?rand=' + res.data.data.rand).then(res => {
          if (res.data.data.user) {
            clearInterval(s.current);
            if (res.data.data.user.auth === 2) {
              alert('您没有权限');
              window.location.reload();
            } else {
              localStorage.setItem('msd_avatar', res.data.data.user.avatar);
              localStorage.setItem('msd_token', res.data.data.user.token);
              localStorage.setItem('msd_name', res.data.data.user.nickname);
              localStorage.setItem('msd_auth', res.data.data.user.auth);
              Global.effect.setLogin({
                avatar: res.data.data.user.avatar,
                token: res.data.data.user.token,
                name: res.data.data.user.nickname,
                auth: res.data.data.user.auth
              });
              setCode(null);
            }
          }
        });
      }, 1000);
    });
  };

  if (!Global.state.login?.token && !code) {
    getCode();
  }

  const handleExit = () => {
    setCode(null);
    Global.effect.setLogin(null);
    localStorage.clear();
  };

  const handleCancel = () => {
    alert('请登录');
  };

  return (
    <div style={{height: '100%', marginLeft: 'auto', width: 'fit-content'}}>
      {
        Global.state.login?.token ?
          (
            <>
              <img src={Global.state.login.avatar} alt=''
                   style={{display: 'inline-block', height: '70%', marginRight: '20px', borderRadius: '100%'}}/>
              <span>{Global.state.login.name}</span>
              <Button onClick={handleExit} style={{marginLeft: '40px'}}>退出</Button>
            </>
          ) :
          <Modal
            title="扫码登录"
            visible={true}
            onCancel={handleCancel}
            footer={[]}
          >
            <img style={{display: 'block', margin: '40px auto', width: '40%'}} src={code} alt=""/>
          </Modal>
      }
    </div>

  );
}

export default Login;